package org.lionsoul.ip2region;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * @author koma <komazhang@foxmail.com>
 * @date 2019-12-26
 */
@Configuration
@EnableConfigurationProperties(Ip2RegionProperties.class)
@ConditionalOnClass(DbSearcher.class)
public class Ip2RegionAutoConfiguration {
    private static final Log LOGGER = LogFactory.getLog(Ip2RegionAutoConfiguration.class);

    public static final String IP2REGION_DBSEARCHER_BEAN_NAME = "ip2regionSearcher";

    @Bean(name = IP2REGION_DBSEARCHER_BEAN_NAME)
    @ConditionalOnProperty(prefix = Ip2RegionProperties.PREFIX, name = "enabled", havingValue = "true")
    public Ip2regionSearcher autoIp2regionSearcher(@Autowired Ip2RegionProperties properties) {
        try {
            File file = ResourceUtils.getFile("classpath:"+properties.getDbfile());
            return new Ip2regionSearcher(new DbSearcher(new DbConfig(), file.getAbsolutePath()));
        } catch (DbMakerConfigException e) {
            //默认配置下忽略此异常
        } catch (FileNotFoundException e) {
            LOGGER.error("Ip2regionSearcher can not find db file in the path ["+properties.getDbfile()+"]");
        }
        return null;
    }
}
